/**
 * 菜单的嵌套渲染
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/6/25
 */
import type { IMenu } from '@/store/useMenu'
import { createVNode, defineComponent } from '@vue/runtime-core'
import { h, resolveComponent } from 'vue'
import IconView from '@/components/icon/icon'

export const MenuRender = defineComponent({
    name: 'menuRender',
    props: {
        item: {
            type: Object,
            required: true,
        },
    },
    emits: ['route'],
    setup({ item }, { emit }) {
        const rule = item as any as IMenu
        let view: any

        const handleRoute = (route: IMenu) => {
            return () => {
                emit('route', route)
            }
        }

        const iconRender = (icon?: string) => {
            if (icon === undefined || icon === '') {
                return ''
            }

            return createVNode(IconView, { name: icon })
        }

        const itemRender = (n: IMenu[]) => {
            const itemNode = []
            for (const m in n) {
                itemNode.push(createVNode(MenuRender, { item: n[m], onRoute: (arg: any) => emit('route', arg) }))
            }

            return itemNode
        }

        if (rule.children && rule.children.length > 0) {
            view = createVNode(
                resolveComponent('el-sub-menu'),
                { index: rule.name },
                {
                    title: () => [iconRender(rule.icon), h('span', rule.title)],
                    default: () => itemRender(rule.children!),
                },
            )
        } else {
            view = createVNode(
                resolveComponent('el-menu-item'),
                { index: rule.name, onClick: handleRoute(rule) },
                {
                    title: () => [iconRender(rule.icon), h('span', rule.title)],
                },
            )
        }

        return () => view
    },
})
